<!-- 创建新企业 -->
<template>
  <div>
    <div class="edit-main" ref="registerBox">
      <Row class="home-page-content">
        <h3>
          <BtnBox isIcon type="light-blue" text="返回" @BtnClick="backHone()" />
          <span v-if="isNew == 1">注册新企业</span>
          <span v-else
            >修改{{ type === "rule" ? "企业收益规则" : "企业信息" }}</span
          >
        </h3>
      </Row>
      <div class="page-select-existing-enterprise page-next">
        <Form
          :model="formData"
          :rules="ruleValidate"
          ref="FormRef"
          label-position="top"
          @on-validate="formValidate"
        >
          <Row type="flex" :gutter="20">
            <Col span="18">
              <h3 ref="companyBase">企业基本信息</h3>
            </Col>
            <Col span="8">
              <FormItem label="公司名称" prop="companyName">
                <Input
                  v-model="formData.companyName"
                  placeholder="请输入公司名称"
                ></Input>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem label="证件类型" prop="companyCardTypeName">
                <Select
                  v-model="formData.companyCardTypeName"
                  placeholder="请选择证件类型"
                >
                  <Option
                    v-for="item in companyCard"
                    :value="item.name"
                    :key="item.dictId"
                    >{{ item.name }}</Option
                  >
                </Select>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem label="证件号码" prop="companyCardNumber">
                <Input
                  v-model="formData.companyCardNumber"
                  placeholder="请输入证件号码"
                ></Input>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem label="注册地址" prop="companyAddress">
                <Input
                  v-model="formData.companyAddress"
                  placeholder="请输入注册地址"
                ></Input>
              </FormItem>
            </Col>
            <Col span="18">
              <FormItem label="上传证件照片" prop="companyIdFiles">
                <ViewImageList
                  v-if="formData.companyIdFiles.length"
                  :echoFile="formData.companyIdFiles"
                  @delImge="delPhotoImge"
                />
                <UploadDrag v-else @uploadSuccess="uploadPhotoSuccess" />
              </FormItem>
            </Col>
            <Col span="18">
              <FormItem label="业务范围">
                <Input
                  v-model="formData.businessRange"
                  type="textarea"
                  :rows="5"
                  placeholder="请输入业务范围"
                  class="auto-textarea"
                ></Input>
              </FormItem>
            </Col>
            <Col span="18">
              <FormItem label="上级组织">
                <div class="select-company">
                  <CompanySelect
                    v-model="formData.parentName"
                    @getData="getParent"
                  />
                </div>
              </FormItem>
            </Col>
            <Divider />
            <Col span="18">
              <h3 ref="companyService">企业服务能力</h3>
            </Col>
            <Col span="18">
              <FormItem label="产业标记" prop="serviceType">
                <CheckboxGroup v-model="formData.serviceType">
                  <Checkbox
                    :label="item.dictId"
                    v-for="item in companyService"
                    :key="item.dictId"
                    >{{ item.name }}</Checkbox
                  >
                </CheckboxGroup>
              </FormItem>
            </Col>
            <!-- <Col span="18">
            <h3>服务地区</h3>
          </Col>-->
            <Col span="18">
              <FormItem label="服务地区" prop="companyServiceAreaList">
                <Row :gutter="20">
                  <Col span="24">
                    <div
                      class="select-city"
                      v-for="(item, index) in areaList"
                      :key="item.id"
                    >
                      <Select
                        v-model="item.provinceValue"
                        style="width: 200px; margin-right: 20px"
                        placeholder="请选择省份"
                        label-in-value
                        clearable
                        @on-change="provinceChange($event, item, index)"
                      >
                        <Option
                          v-for="item in provinceList"
                          :value="item.id"
                          :key="item.id"
                          >{{ item.name }}</Option
                        >
                      </Select>
                      <Select
                        v-model="item.cityValue"
                        placeholder="请选择市"
                        label-in-value
                        clearable
                        @on-change="cityChange($event, index)"
                      >
                        <Option
                          v-for="item in item.cityList"
                          :value="item.id"
                          :key="item.id"
                          >{{ item.name }}</Option
                        >
                      </Select>
                      <div class="action-btn">
                        <span @click="addCity(index)">
                          <Icon type="md-add-circle" :size="20" />
                        </span>
                        <span
                          @click="delCity(index)"
                          v-if="areaList.length > 1"
                        >
                          <Icon type="md-remove-circle" :size="20" />
                        </span>
                      </div>
                    </div>
                  </Col>
                </Row>
              </FormItem>
            </Col>
            <Col span="18">
              <h3>企业资质</h3>
            </Col>
            <Col span="18">
              <FormItem label="上传资质">
                <UploadAptitude
                  ref="UploadAptitude"
                  @handleOk="handleAction"
                  @handleUpdetaOk="handleUpdetaOk"
                >
                  <div
                    class="update-photo-btn"
                    v-if="formData.companyAptitudeFiles.length"
                  >
                    <BtnBox iconName="icon_3" boxWidth="96" text="点击添加" />
                  </div>
                  <div class="update-photo" v-else>点击添加</div>
                </UploadAptitude>
                <div
                  class="aptitude-list"
                  v-if="formData.companyAptitudeFiles.length"
                >
                  <Table
                    :columns="columns"
                    :data="formData.companyAptitudeFiles"
                  >
                    <template slot-scope="{ row }" slot="ImgAction">
                      <ViewImageList
                        v-if="row.files && row.files.length"
                        isViewBtn
                        :echoFile="row.files"
                      />
                    </template>
                    <template slot-scope="{ row, index }" slot="action">
                      <BtnText
                        type="primary"
                        @BtnClick="editAptitude(row, 1, index)"
                        >修改</BtnText
                      >
                      <BtnText
                        type="error"
                        @BtnClick="editAptitude(row, 2, index)"
                        >删除</BtnText
                      >
                    </template>
                  </Table>
                </div>
              </FormItem>
            </Col>
          </Row>

          <Row :gutter="20">
            <Col span="18">
              <h3>企业收益规则</h3>
            </Col>
            <Col span="8">
              <FormItem label="收益规则" prop="companyDivideIntoRuleValue">
                <InputNumber
                  style="width: 100%"
                  v-model="formData.companyDivideIntoRuleValue"
                  placeholder="请输入分层规则"
                />
              </FormItem>
            </Col>
            <Col span="8"></Col>
            <Col span="18">
              <FormItem label="上传规则说明" prop="companyRuleFiles">
                <ViewImageList
                  v-if="formData.companyRuleFiles.length"
                  :echoFile="formData.companyRuleFiles"
                  @delImge="delDivideIntoRuleFile"
                />
                <UploadDrag
                  v-else
                  @uploadSuccess="uploadDivideIntoRuleFileSuccess"
                />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="18">
              <Button
                type="primary"
                :disabled="isBtnDisabled"
                :loading="isLoading"
                @click="handleAgree"
                >提交</Button
              >
            </Col>
          </Row>
        </Form>
      </div>
    </div>
  </div>
</template>

<script>
import {
  GetNationAreaByParentId,
  GetDict, // 获取证件类型
  GetCompanySelectByCompanyService, // 根据产业标记获取组织
} from "@/api/common.js";

import UploadAptitude from "@/pages/account/register/components/uploadAptitude.vue";
import CheckCompany from "@/pages/account/register/components/checkCompany.vue";
import { myCompanyInfo, updateCompanyInfo } from "@/api/enterpriseManage.js";
import CompanySelect from "@/pages/components/companySelect";

export default {
  components: {
    UploadAptitude,
    CheckCompany,
    CompanySelect,
  },
  data() {
    const validatecompanyIdFiles = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传照片"));
      } else {
        callback();
      }
    };

    const validateCompanyServiceType = (rule, value, callback) => {
      if (value && value.length) {
        callback();
      } else {
        callback(new Error("请选择产业标记！"));
      }
    };

    const validateCompanyProvince = (rule, value, callback) => {
      if (this.areaList.length) {
        for (let item in this.areaList) {
          // if (!this.areaList[item].cityValue) {
          //   callback(new Error("请选择服务城市！"));
          // }
          let provinceValue = this.areaList[item].provinceValue;
          let cityValue = this.areaList[item].cityValue;
          let lenP = this.areaList.filter(
            (o) => o.provinceValue == provinceValue && o.cityValue == cityValue
          ).length;
          if (lenP > 1) {
            callback(new Error("选择地区重复！"));
            break;
          }
          if (!this.areaList[item].provinceValue) {
            callback(new Error("请选择服务省份！"));
          }
        }
        callback();
      } else {
        callback(new Error("请选择服务地区！"));
      }
    };

    return {
      isBtnDisabled: false,
      modelValue: "",
      isHide: false,
      areaList: [
        {
          id: Date.now(),
          provinceValue: "",
          provinceName: "",
          cityValue: "1",
          cityName: "",
          cityList: [],
        },
      ],
      provinceList: [],
      formData: {
        // 注册新公司基本信息
        companyId: "", // 公司id
        companyName: "", // 公司名称
        companyCardTypeName: "", // 营业执照
        companyCardNumber: "", // 营业执照编号
        companyAddress: "", // 注册地址
        companyIdFiles: [], // 证件图片
        businessRange: "", // 经营范围
        parentId: "", // 上级公司ID
        parentName: "", // 上级公司ID
        serviceType: [], // 公司服务类型
        serviceArea: [], // 企业地址
        companyAptitudeFiles: [], // 企业资质
        companyDivideIntoRuleValue: 0, // 收益规则
        companyRuleFiles: [], // 收益规则文件
        status: "",
      },
      ruleValidate: {
        companyName: [
          { required: true, message: "请输入公司名称", trigger: "change" },
        ],
        companyCardTypeName: [
          { required: true, message: "请选择证件类型", trigger: "change" },
        ],
        companyCardNumber: [
          { required: true, message: "请输入证件号码", trigger: "change" },
        ],
        companyAddress: [
          { required: true, message: "请输入注册地址", trigger: "change" },
        ],
        companyIdFiles: [
          {
            required: true,
            validator: validatecompanyIdFiles,
            trigger: "change",
          },
        ],
        serviceType: [
          {
            required: true,
            validator: validateCompanyServiceType,
            message: "请选择产业标记",
            trigger: "change",
          },
        ],
        companyServiceAreaList: [
          {
            required: true,
            validator: validateCompanyProvince,
            trigger: "blur",
          },
        ],
      },
      docType: [], // 证件类型
      docType: [],
      parentCompanyList: [], // 上级产业
      companyService: [], // 公司服务能力
      companyCard: [], // 证件类型
      columns: [
        {
          title: "资质名称",
          key: "companyAptitudeName",
        },
        {
          title: "等级",
          key: "lv",
        },
        {
          title: "资质附件",
          slot: "ImgAction",
        },
        {
          title: "有效期截至日期",
          key: "validEndDate",
        },
        {
          title: "操作",
          slot: "action",
        },
      ],
      currentIndex: 0,
      isLoading: false,
      type: "",
      baseTop: 0,
      setviceTop: 0,
      isTop: 0,
      isVerify: false,
      isNew: "",
    };
  },
  methods: {
    formValidate(prop, status, error) {
      let companyBase = [
        "companyName",
        "companyCardTypeName",
        "companyCardNumber",
        "companyAddress",
        "companyCardFile",
      ];
      let companyService = ["serviceType", "companyServiceAreaList"];
      if (error && this.isTop == 0) {
        this.$Message.error(error);
      }
      if (companyBase.includes(prop) && !status && this.isVerify) {
        this.isTop = 1;
        this.isVerify = false;
        this.$refs.registerBox.scrollTop = this.baseTop;
        return;
      }
      if (
        companyService.includes(prop) &&
        !status &&
        this.isVerify &&
        this.isTop == 0
      ) {
        this.isTop = 1;
        this.isVerify = false;
        this.$refs.registerBox.scrollTop = this.setviceTop;
        return;
      }
    },
    async getNationAreaData(dataKey, params = {}) {
      let data = await GetNationAreaByParentId(params);
      if (dataKey == "provinceList") {
        this.provinceList = data;
      }
      if (dataKey == "cityList") {
        let resData = [
          {
            id: "1",
            name: "全部",
          },
        ].concat(data);
        this.areaList[params.index].cityList = resData;
        this.areaList[params.index].cityValue = "1";
        this.areaList[params.index].cityName = "全部";
      }
    },
    async getDictData(key, name) {
      let data = await GetDict({
        parentId: key,
      });
      this[name] = data;
    },
    // 获取上级组织
    async getCompanySelectByCompanyServiceData(companyServiceTypeId) {
      let params = {
        companyServiceTypeId,
      };
      let data = await GetCompanySelectByCompanyService(params);
    },

    // 切换省市
    provinceChange(e, item, index) {
      let params = {};
      if (item.provinceValue) {
        this.areaList[index].provinceName = e.label;
        params = {
          parentId: item.provinceValue,
          index,
        };
      }
      this.getNationAreaData("cityList", params);
    },
    cityChange(e, index) {
      this.areaList[index].cityName = e ? e.label : "";
    },
    addCity() {
      this.areaList.push({
        id: Date.now(),
        provinceValue: "",
        provinceName: "",
        cityValue: "1",
        cityName: "",
        cityList: [],
      });
    },
    delCity(index) {
      this.areaList.splice(index, 1);
    },
    uploadPhotoSuccess(file) {
      this.formData.companyIdFiles = [file];
      this.$refs["FormRef"].validateField("companyIdFiles");
    },
    handleUpdetaOk(item) {
      item.files = [item.fileVo];
      delete item.fileVo;
      this.$set(this.formData.companyAptitudeFiles, this.currentIndex, item);
    },
    // 删除照片
    delPhotoImge(index) {
      this.formData.companyIdFiles = [];
      this.$refs["FormRef"].validateField("companyIdFiles");
    },
    // 添加企业资质
    handleAction(item) {
      item.files = [item.fileVo];
      delete item.fileVo;
      this.formData.companyAptitudeFiles.push(item);
    },
    // 新增修改资质
    editAptitude(item, type, index) {
      // 修改
      if (type == 1) {
        this.currentIndex = index;
        item.fileVo = item.files[0] || {};
        this.$refs.UploadAptitude.showModal(item);
      }
      // 删除
      if (type == 2) {
        this.formData.companyAptitudeFiles.splice(index, 1);
      }
    },
    // 删除分层规则文件
    delDivideIntoRuleFile(index) {
      this.formData.companyRuleFiles.splice(index, 1);
    },
    // 添加分层规则文件
    uploadDivideIntoRuleFileSuccess(item) {
      this.formData.companyRuleFiles = [item];
    },

    // 选择企业
    serviceChange(value) {
      // 获取企业
      this.getCompanySelectByCompanyServiceData(value);
    },
    handleAgree() {
      this.isTop = 0;
      this.isVerify = true;
      this.$refs["FormRef"].validate(async (valid) => {
        if (valid) {
          const request = {
            ...this.formData,
            parentName: this.formData.parentId ? this.formData.parentName : "",
            serviceArea: this.areaList.map((it) => {
              return {
                cityName: it.cityName,
                cityCode: it.cityValue == "1" ? "" : it.cityValue,
                provinceCode: it.provinceValue,
                provinceName: it.provinceName,
              };
            }),
            serviceType: this.companyService
              .filter((it) => {
                return this.formData.serviceType.includes(it.dictId);
              })
              .map((it) => {
                return {
                  serviceTypeId: it.dictId,
                  serviceTypeName: it.name,
                };
              }),
          };

          try {
            this.isLoading = true;

            await updateCompanyInfo(request);
            this.isLoading = false;
            this.$Message.success("修改成功");

            this.$router.replace({ path: "/myEnterprise" });
          } catch (error) {
            this.isLoading = false;
          }
        } else {
          // this.$Message.error("信息验证不通过");
        }
      });
    },
    // 初始化请求接口
    bsaeApi() {
      this.getNationAreaData("provinceList", {}); // 获取省市区
      this.getDictData("COMPANY_CARD_TYPE", "companyCard"); // 获取证件类型
      this.getDictData("COMPANY_SERVICE", "companyService"); // 获取公司服务能力
    },
    backHone() {
      if (this.isNew == 1) {
        this.$router.push({
          name: "home",
        });
      } else {
        this.$router.push({
          name: "myEnterprise",
        });
      }
    },
    getParent(companyId) {
      this.formData.parentId = companyId || "";
    },
  },
  async created() {
    this.bsaeApi();

    this.type = this.$route.query.type;
    this.isNew = this.$route.query.isNew;
    const typeObj = { all: 0, info: 1, rule: 2 };
    this.formData.companyUpdateType = typeObj[this.type];
    if (this.isNew != 1) {
      const info = await myCompanyInfo({});
      Object.keys(this.formData).forEach((k) => {
        if (info[k]) {
          this.formData[k] = info[k];
        }
      });

      this.formData.serviceType = info.serviceType.map(
        (it) => it.serviceTypeId
      );

      // 地区给了默认值, 防止没有地区,页面不显示问题
      if (info.serviceArea && info.serviceArea.length) {
        this.areaList = [];
      }

      info.serviceArea.forEach(async (it) => {
        const cityList = await GetNationAreaByParentId({
          parentId: it.provinceCode,
        });
        cityList.unshift({ id: "1", name: "全部" });
        this.areaList.push({
          id: Date.now(),
          cityName: it.cityName,
          cityValue: it.cityCode ? it.cityCode : "1",
          provinceValue: it.provinceCode,
          provinceName: it.provinceName,
          cityList,
        });
      });
    }
  },
  mounted() {
    this.baseTop = this.$refs.companyBase.getBoundingClientRect().top - 133;
    this.setviceTop =
      this.$refs.companyService.getBoundingClientRect().top - 133;
  },
};
</script>

<style lang="less" scoped>
.page-select-existing-enterprise {
  padding: 20px;
  background: #fff;
  h3 {
    font-size: 18px;
    margin-bottom: 20px;
  }
}

.select-company {
  display: flex;
  border: 1px solid #c4c4c4;
  border-radius: 4px;
  ::v-deep(.ivu-select-selection) {
    border: none;
  }
}

.select-company-item {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  margin-top: 20px;
  border: 1px solid #c4c4c4;
  border-radius: 4px;
}
.next-btn {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
// .ivu-btn {
//   width: 100%;
// }

.select-city {
  display: flex;
  position: relative;
  margin-bottom: 20px;
  .action-btn {
    position: absolute;
    right: 0;
    transform: translateX(100%);
    height: 100%;
    display: flex;
    align-items: center;
    span {
      display: block;
      margin-left: 10px;
      cursor: pointer;
    }
  }
}
.ivu-input,
.ivu-select-selection {
  background: #fff;
}

.update-photo {
  text-align: center;
  background: #eee;
  border-radius: 2px;
  flex: none;
  height: 80px;
  line-height: 80px;
  width: 100%;
  cursor: pointer;
}

.aptitude-list {
  margin-top: 15px;
}
.home-page-content {
  margin-bottom: 15px;
  h3 {
    display: flex;
    align-items: center;
  }
  span {
    margin-left: 10px;
  }
}
.edit-main {
  height: calc(~"100vh - 133px");
  overflow: auto;
}
</style>
